package com.intellij.licensecommon.net.impl;

import com.intellij.licensecommon.net.Address;
import com.intellij.licensecommon.net.NetworkSocket;
import com.intellij.licensecommon.net.NetworkSocketFactory;
import com.intellij.licensecommon.net.c;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

public class d implements NetworkSocketFactory {
    public NetworkSocket a(Address paramAddress)
            throws c {
        if (paramAddress == null) {
            throw new c("Address cannot be null.");
        }
        try {
            b localb = (b) paramAddress;
            return new SocketImpl(new DatagramSocket(localb.getStocketAddress()), SocketImpl.e);
        } catch (SocketException localSocketException) {
            throw new c(paramAddress.toString(), localSocketException);
        }
    }

    public NetworkSocket b(Address paramAddress) throws c {
        try {
            b localb = (b) paramAddress;
            InetSocketAddress localInetSocketAddress = localb.getStocketAddress();
            MulticastSocket localMulticastSocket = new MulticastSocket(localInetSocketAddress.getPort());
            Enumeration localEnumeration = NetworkInterface.getNetworkInterfaces();
            while (localEnumeration.hasMoreElements()) {
                NetworkInterface localNetworkInterface = (NetworkInterface) localEnumeration.nextElement();
                if (a(localNetworkInterface)) {
                    localMulticastSocket.joinGroup(localInetSocketAddress, localNetworkInterface);
                }
            }
            return new SocketImpl(localMulticastSocket, SocketImpl.e);
        } catch (IOException localIOException) {
            throw new c(localIOException);
        }
    }

    private static boolean a(NetworkInterface ni) throws SocketException {
        Enumeration<InetAddress> addresses = ni.getInetAddresses();
        if (!addresses.hasMoreElements()) {
            return false;
        }
        if ((ni.isLoopback()) || (ni.isPointToPoint()) || (ni.isVirtual())) {
            return false;
        }

        do {
            InetAddress address = addresses.nextElement();
            if (address.getAddress().length == 4) {
                return true;
            }
        } while (addresses.hasMoreElements());

        return false;
    }

    public NetworkSocket a() throws c {
        try {
            return new SocketImpl(new DatagramSocket(new InetSocketAddress(InetAddress.getLocalHost(), 0)), SocketImpl.e);
        } catch (Exception localException) {
            throw new c(localException);
        }
    }
}

